package com.why.util;

import com.alibaba.fastjson.JSON;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class JsonUtils {

//    public static  <T> List<T> readResourceJson(String path, String fileName, Class<T> clazz){
//
//    }

    public static <T> List<T> readJson(String path, String fileName, Class<T> clazz) throws IOException {
        File file = new File(path + fileName);
        if (!file.exists()) {
            return new ArrayList<>();
        }
        StringBuilder laststr = new StringBuilder();
        String tempString = null;
        int line = 1;

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                System.out.println("line " + line + ": " + tempString);
                laststr.append(tempString);
                line++;
            }
        }
        return JSON.parseArray(laststr.toString(), clazz);
    }


    public static <T> void writeJson(String path, String fileName, List<T> ts) throws IOException {
        File filePath = new File(path);
        if (!filePath.exists()) {
            if (!filePath.mkdir()) {
                System.out.println(path);
            }
        }
        File file = new File(path + fileName);
        if (!file.exists()) {
            if (!file.createNewFile()) {
                System.out.println(path + fileName);
            }
        }

        try (PrintWriter out = new PrintWriter(file)) {
            out.write(JSON.toJSONString(ts));
            System.out.println(JSON.toJSONString(ts));
            out.flush();
        }
    }
}
